package xin.yangshuai.zookeeper01.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

public class DistributeServer {

    // 注意：逗号左右不能有空格
    private String connectString = "192.168.145.132:2181,192.168.145.133:2181,192.168.145.134:2181";
    // 2000毫秒
    private int sessionTimeout = 2000;

    private ZooKeeper zkClient;

    private String node;

    public void getConnect() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }

    // 注册
    public void register() throws KeeperException, InterruptedException {
        // 创建一个带序号的临时节点
        // 提前创建好 /servers 节点
        node = zkClient.create("/servers/server", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("服务器 " + node + " 注册成功");
    }

    // 断开连接
    public void close() throws InterruptedException {
        System.out.println("服务器 " + node + " 下线");
        zkClient.close();
    }

}
